package org.asdtiang.exceldemo;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.asdtiang.exceldemo.repository.ArmyJobRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import org.asdtiang.exceldemo.domain.ArmyJob;

@Service
public class InitData implements ApplicationContextAware {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private static ApplicationContext context;
	@Autowired
	private ArmyJobRepository armyJobRepository;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return context;
	}

	@PostConstruct
	public void init() {
		AtomicInteger idInt = new AtomicInteger(1);
		if(armyJobRepository.count()>1000) {
			return;
		}
		try {
			// InputStream inp = new FileInputStream("workbook.xlsx");
			Resource resource = context.getResource("classpath:16972086ec894481190432.xlsx");
			Workbook wb = WorkbookFactory.create(resource.getInputStream());
			Sheet sheet = wb.getSheetAt(0);
			int i = 6;
			Field[] fields = ArmyJob.class.getDeclaredFields();
			List<ArmyJob> saveList = new ArrayList<>();
			for (; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				ArmyJob aj = new ArmyJob();
				aj.setId(idInt.getAndIncrement());
				//aj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
				for (int j = 0; j < fields.length; j++) {
					ExcelCellIndexAnnotaion ann = fields[j].getAnnotation(ExcelCellIndexAnnotaion.class);
					if (ann != null) {
						fields[j].set(aj, row.getCell(ann.index()).toString());
					}
				}
				saveList.add(aj);
				if (i % 1000 == 0) {
					armyJobRepository.saveAll(saveList);
					logger.info("save to es-->"+saveList.size());
					saveList.clear();
				}

			}
			armyJobRepository.saveAll(saveList);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
